<?php


namespace app\wechat\controller;


use app\BaseController;
use app\common\model\Order;
use app\common\model\Finance;
use app\common\model\UserBook;
use Psr\Cache\CacheException;
use think\cache\driver\Redis;
use think\facade\Cache;
use think\facade\Db;
use think\exception\ValidateException;
class Qian extends AuthBase
{
    protected $noLogin = ['finance_index'];
    /**\
     * @return \think\response\Json
     * 订单列表
     */
    public function order_index()
    {
        $type = input('get.type');
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 50, 'intval');
        $search = input('param.search');
        $where=[];
        if($search){
            $where[] = [
                'o.order_no|u.nickname', 'like',  "%".$search."%"
            ];
        }
        $where[] = [
            'o.type', '=',  $type
        ];
        $model = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.student_id=u.id')
            ->where('o.status','<>',10)
            ->order('o.create_time DESC')
            ->page($page, $limit)
            ->column('o.id,u.nickname,u.id as user_id,u.head_img,o.type,o.price,o.yet_price,o.order_no,o.name,o.status,o.send_price,o.software_ask_one,o.software_ask_two,o.software_ask_three');
        foreach ($model as $key => $value) {
            $model[$key]['yet_send_price'] = Db::name('finance')->where(['order_id'=>$value['id'],'type'=>2,'status'=>4])->sum('price');
        }
        $count = Order::where($where)
            ->alias('o')
            ->where('o.status','<>',10)
            ->leftJoin('user u','o.student_id=u.id')
            ->count();
        $data['total'] = $count;
        $data['list'] = $model;
        $data['page'] = $page;
        return $this->show(1, '', $data);
    }
    /**\
     * @return \think\response\Json
     * 退单列表
     */
    public function order_cancel_index()
    {
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 50, 'intval');
        $search = input('param.search');
        $where=[];
        if($search){
            $where[] = [
                'o.order_no|u.nickname', 'like',  "%".$search."%"
            ];
        }
        $where[] = [
            'o.status', '=',  10
        ];
        $model = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.student_id=u.id')
            ->order('o.create_time DESC')
            ->page($page, $limit)
            ->column('o.id,o.price,o.order_no,o.name,o.status,o.send_price');
        foreach ($model as $key => $value) {
            $model[$key]['yet_send_price'] = Db::name('finance')->where(['order_id'=>$value['id'],'type'=>2,'status'=>4])->sum('price');
            $model[$key]['xu_send_price'] = Db::name('finance')->where(['order_id'=>$value['id'],'type'=>2,'status'=>[2,3]])->sum('price');
        }
        $count = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.student_id=u.id')
            ->count();
        $data['total'] = $count;
        $data['list'] = $model;
        $data['page'] = $page;
        return $this->show(1, '', $data);
    }
    /**
     * 学生信息列表
     */
    public function student_index()
    {
        $type = input('get.type');
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 50, 'intval');
        $search = input('param.search');
        $where=[];
        if($search){
            $where[] = [
                'o.order_no|u.nickname', 'like',  "%".$search."%"
            ];
        }
        $where[] = [
            'o.type', '=',  $type
        ];
        $model = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.student_id=u.id')
            ->where('o.status','<>',10)
            ->order('o.create_time DESC')
            ->page($page, $limit)
            ->column('o.id,u.nickname,u.id,u.head_img,o.price,o.yet_price,o.order_no,o.name,o.status');
        $count = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.student_id=u.id')
            ->where('o.status','<>',10)
            ->count();
        $data['total'] = $count;
        $data['list'] = $model;
        $data['page'] = $page;
        return $this->show(1, '', $data);
    }
    /**\
     * @return \think\response\Json
     * 财务列表
     */
    public function finance_index()
    {
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 50, 'intval');
        // $search = input('param.search');
        $where=[];
        // if($search){
        //     $where[] = [
        //         'f.order_no|u.nickname', 'like',  "%".$search."%"
        //     ];
        // }
        //判断是否有结算中的订单
        $pay=Db::name('finance_pay')->where('status',1)->count();
        if($pay){
            $where[] = [
                'f.status', '=',  3
            ];
            $data['status']=2;
        }else{
            $where[] = [
                'f.status', '=',  2
            ];
            $data['status']=1;
        }
        $where[] = [
            'f.type', '=',  2
        ];
        $model = Finance::where($where)
            ->alias('f')
            ->leftJoin('order o','f.order_id=o.id')
            ->order('f.create_time DESC')
            ->page($page, $limit)
            ->column('f.id,o.order_no,o.id as order_id,o.status,o.price as order_price,o.send_price,f.price,f.order_status');
        $data['total_yet_send_price']=0;
        foreach ($model as $key => $value) {
            $total=Db::name('finance')->where(['order_id'=>$value['order_id'],'type'=>2,'status'=>4])->sum('price');
            $data['total_yet_send_price']+=$total;
            $model[$key]['yet_send_price'] = $total;
        }
        $count = Finance::where($where)
            ->alias('f')
            ->leftJoin('order o','o.id=f.order_id')
            ->count();
        //计算总数
        $data['total_price'] = Finance::where(['status'=>[2,3],'type'=>2])
            ->sum('price');
        $data['total'] = $count;
        $data['list'] = $model;
        $data['page'] = $page;
        return $this->show(1, '', $data);
    }
    /**
     * 财务结款
     */
    public function finance_pay(){
        //判断是否可以
        $res=Db::name('finance_pay')->where('status',1)->find();
        if($res){
            return $this->show(0,'上一笔待确认中');
        }
        //找到所有待借款的订单
        $finance=Db::name('finance')->where(['status'=>2,'type'=>2])->column('id');
        if (!$finance){
            return show(0,'当前没有需要结款的订单');
        }
        Db::startTrans();
        try {
        //把所有订单改为结算中
            Db::name('finance')->where(['status'=>2,'type'=>2])->update(['status'=>3]);
            Db::name('finance_pay')
                ->insert(['ids'=>implode(",",$finance),'status'=>1,'create_time'=>time(),'update_time'=>time()]);
            Db::commit();
            return show(1, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    //学生列表
    public function student_list(){
        $search=input('get.search');
        $where=[];
        if($search){
            $where[]=['nickname|id','like',"%".$search."%"];
        }
        $where[]=['type','=',1];
        $where[]=['order_id','=',0];
        $model=Db::name('user')
            ->where($where)
            ->column('id,nickname,head_img');
        return show(1,'',$model);
    }
    /**
     * 创建订单
     */
    public function create_order(){
        $data=input('post.');
        try {
            validate(\app\common\validate\Record::class)
                ->scene("create_order")
                ->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->show(0, $e->getError());
        }
        $user=Db::name('user')->where(['id'=>$data['student_id'],'type'=>1,'order_id'=>0])->find();
        if(!$user){
            return show(0,'此身份状态无法创建订单');
        }
        if ($data['send_price']>$data['price']){
            return $this->show(0,'派单价格不能大于订单价格');
        }
        Db::startTrans();
            try {
                $autoIncrement = Db::query("
                SELECT AUTO_INCREMENT 
                FROM information_schema.tables 
                WHERE table_schema = 'lunwen' 
                AND table_name = 'bingdi_order'
            ");
            $nextId = $autoIncrement[0]['AUTO_INCREMENT'];
            if (empty($data['order_no'])){
                $orderNumber = "kz".str_pad($nextId % 10000, 5, '0', STR_PAD_LEFT); // 输出00123
            }else{
                $orderNumber = $data['order_no'];
            }
            $res=Db::name('order')->where('order_no',$orderNumber)->find();
            if ($res){
                return show(0,'订单号重复');
            }
//            $orderNumber = str_pad($nextId % 10000, 5, '0', STR_PAD_LEFT); // 输出00123
            //生成订单,学生order_id绑定.就没了
            $order_id=Db::name('order')->insertGetId([
                'order_no'=>$orderNumber,
                'student_id'=>$data['student_id'],
                'price'=>$data['price'],
                'send_price'=>$data['send_price'],
                'type'=>$data['type'],
                'major'=>$data['major'],
                'software_ask_one'=>$data['software_ask_one'],
                'software_ask_two'=>$data['software_ask_two'],
                'software_ask_three'=>$data['software_ask_three'],
                'school_level'=>$data['school_level'],
                'information'=>$data['information'],
                'middle_date'=>strtotime($data['middle_date']),
                'end_date'=>strtotime($data['end_date']),
                'name'=>$data['name'],
            ]);
            Db::name('user')->where(['id'=>$data['student_id']])->update(['order_id'=>$order_id]);
            Db::commit();
            return show(1, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    /**
     * 修改订单价格和收款
     */
    public function edit_price(){
        $data=input('post.');
        $order=Db::name('order')->where(['id'=>$data['id']])->find();
        //判断订单状态是否可以修改价格
        if($order['status']>=2&&$data['yet_price']==0){
            return show(0,'订单状态不允许修改价格') ;
        }
        if($order['price']<=0||$data['send_price']<=0||$data['price']<$data['send_price']||$data['yet_price']<0){
            return show(0,'价格填写有误') ;
        }
        if ($data['yet_price']>$order['price']){
            return show(0,'收款不能大于订单价格');
        }
        $yet_price=$data['yet_price']+$order['yet_price'];
        if ($yet_price>$order['price']){
            return show(0,'累积收款不能大于订单价格');
        }
        Db::startTrans();
        try {
            if($order['status']==0){
                Db::name('order')->where(['id'=>$data['id']])
                ->inc('yet_price',$data['yet_price'])
                ->update(['price'=>$data['price'],'send_price'=>$data['send_price']]);
            }
            if($order['status']==1){
                Db::name('order')->where(['id'=>$data['id']])
                ->inc('yet_price',$data['yet_price'])
                ->update(['price'=>$data['price'],'send_price'=>$data['send_price']]);
            }
            if($order['status']>=2){
                Db::name('order')->where(['id'=>$data['id']])
                ->inc('yet_price',$data['yet_price'])
                ->update();
            }
            if($data['yet_price']>0){
                //增加财务信息//先增加学生的,再增加管理员的
                Db::name('user')
                ->where(['id'=>$order['student_id']])
                ->inc('yet_price',$data['yet_price'])
                ->update();
                Db::name('finance')
                    ->insert(['name'=>"学生付款",'status'=>1,'order_id'=>$order['id'],'price'=>$data['yet_price'],'type'=>1,'student_id'=>$order['student_id'],
                    'create_time'=>time(),'update_time'=>time(),'pay_time'=>time()]);
                
            }
            if($order['status']==0&&$data['yet_price']>0){
                Db::name('order')->where(['id'=>$data['id']])->update(['status'=>1]);
                //修改管理员的结算记录
                Db::name('finance')
                ->insert(['name'=>"定金付款给管理员",'status'=>2,'order_id'=>$order['id'],'order_status'=>1,
                'price'=>round($data['send_price']*0.3,2),'type'=>2,
                'create_time'=>time(),'update_time'=>time()]);
            }
            Db::commit();
            return show(1, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    /**
     * 退单
     */
    public function refund(){
        $id = input('post.id');
        $res=Db::name('order')
            ->where('id',$id)
            ->update(['status'=>10]);
        if($res){
            return show(1,'退单成功');
        }else{
            return show(0,'退单失败');

        }
    }
    /**
     * 财务总计
     */
    public function finance_statistics(){
        $order_id=Db::name('order')
            ->whereNotIn('status',[0,10])
            ->column('id');
        $data['sum']=Db::name('order')
            ->where('status','<>',10)
            ->sum('price');
        $data['yet_price']=Db::name('order')
            ->where('status','<>',10)
            ->sum('yet_price');
        $data['cost']=Db::name('finance')
            ->where(['order_id'=>$order_id,'type'=>2,'status'=>4])
            ->sum('price');
        $data['profit']=$data['yet_price']-$data['cost'];
        return $this->show(1,'',$data);
    }
    /**
     * 退单
     */
    public function cancel_order(){
        $id=input('post.id');
        Db::startTrans();
        try {
            Db::name('order')
                ->where('id',$id)
                ->update(['status'=>10]);
            //删除未结算的记录
            Db::name('finance')
                ->where(['order_id'=>$id,'status'=>[2,3],'type'=>[2,3]])
                ->delete();
            Db::commit();
            return show(1, '退单成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
}